<template>
  <el-form
    :model="codeForm"
    label-position="top"
    :hide-required-asterisk="true"
    ref="ruleFormRef"
    :rules="rules"
    label-width="0px"
    @submit.native.prevent
  >
    <el-form-item label="" prop="mobile">
      <el-input
        v-model="codeForm.mobile"
        auto-complete="off"
        :placeholder="$t('login.mobliePlaceholder')"
        type="text"
      />
    </el-form-item>
    <el-form-item label="" prop="captcha">
      <x-code-input
        ref="codeInput"
        v-model="codeForm.captcha"
        :type="'moblie'"
        :isRandom="false"
        @refreshCode="getAuthCode"
        @handleEnter="onSubmit()"
        :placeholder="$t('login.codePlaceholder')"
      />
    </el-form-item>
    <el-form-item label-width="76px">
      <el-button type="primary" :loading="loading" size="medium" style="width: 100%" @click.prevent="onSubmit()">
        {{ $t('login.loginBtnLabel') }}
      </el-button>
    </el-form-item>
  </el-form>
</template>
<script>
  import { throttle, checkMobilePhone } from '@package/utils'
  import login from '../pinia/login.js'
  import { apiGetMobileCode } from '../api'

  export default {
    data() {
      return {
        login,
        codeForm: {
          mobile: '',
          captcha: '',
          captchaKey: ''
        },
        loading: false,
        rules: {
          mobile: [
            { required: true, trigger: 'blur', message: '请输入手机号码' },
            { validator: this.validatePhone, trigger: 'blur' }
          ],
          captcha: [
            { required: true, trigger: 'blur', message: '请输入验证码' },
            { validator: this.checkMobliedCode, trigger: 'blur' }
          ]
        },
        verificationCode: ''
      }
    },
    created() {},
    mounted() {},
    methods: {
      getAuthCode() {
        this.$refs.ruleFormRef.validateField('mobile', (valid) => {
          if (!valid) {
            const formData = new FormData()
            formData.append('mobile', this.codeForm.mobile)
            this.$refs.codeInput.refreshTimes()
            apiGetMobileCode(formData).then(({ data }) => {
              this.$message.success(`验证码已发，请注意查收！${data.captcha}`)
              this.verificationCode = data.captcha
              this.codeForm.captchaKey = data.captchaKey
            })
          }
        })
      },
      checkMobliedCode(rule, value, callback) {
        if (value == this.verificationCode) {
          return callback()
        }
        callback(new Error('验证码错误'))
      },
      validatePhone(rule, value, callback) {
        if (value && value !== '' && !checkMobilePhone(value)) {
          callback(new Error(this.$t('system.user.PleasePhoneRight')))
        } else {
          callback()
        }
      },
      /**
       * @param codeForm - 登录表达数据
       * 用户登录
       */
      onSubmit: throttle(function () {
        this.loading = true
        const userLogin = login()
        this.$refs.ruleFormRef.validate((valid, error) => {
          if (valid) {
            const formData = new FormData()
            formData.append('mobile', this.codeForm.mobile)
            formData.append('captcha', this.codeForm.captcha)
            formData.append('grant_type', 'sms')
            formData.append('scope', 'message.read message.write')
            // formData.append('captcha', this.codeForm.captcha)
            formData.append('captchaKey', this.codeForm.captchaKey)
            this.loading = true
            userLogin.LoginIn(formData).then(
              () => {
                this.loading = false
                this.$emit('handleLoginSucess')
              },
              () => {
                this.loading = false
              }
            )
          } else {
            this.loading = false
          }
        })
      }, 1000)
    }
  }
</script>
<style lang="scss" scoped>
  .code-img {
    display: inline;
    margin-left: 16px;
  }
</style>
